<?php namespace App;

use App\Exceptions\NotFoundException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Session;

/**
 * App\Project
 *
 * @property integer $id
 * @property string $project_name
 * @property string $project_intro
 * @property integer $img_proje=ctlogo_id
 * @property string $company_name
 * @property string $province
 * @property string $city
 * @property string $create_time
 * @property integer $field_id
 * @property integer $phase_id
 * @property string $project_status
 * @property string $project_desc
 * @property string $project_lightspot
 * @property string $project_future
 * @property string $project_tags
 * @property integer $file_bp_id
 * @property integer $invet_phase_id
 * @property string $invet
 * @property string $money_type
 * @property integer $sell_stock
 * @property integer $min_money
 * @property integer $invest_num
 * @property string $stop_time
 * @property string $reginv_time
 * @property integer $is_finance
 * @property integer $is_speed_finance
 * @property string $other_desc
 * @property integer $star_layer
 * @property integer $repay_rate
 * @property string $phone
 * @property integer $user_id
 * @property integer $project_auth
 * @property integer $do_status
 * @property integer $url_id
 * @property string $deleted_at
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property string $email
 * @property string $name
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\ProjectNews[] $projectNews
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\ProjectTeam[] $projectTeam
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\ProjectMilestone[] $projectMilestone
 * @property-read \App\Images $toProjectLogo
 * @property-read \App\Files $toBpFile
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\InvestLog[] $investLog
 * @property-read \App\Phases $toPhase
 * @property-read \App\Phases $toInvetPhase
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\User[] $userFocusProject
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Tags[] $project_x_tags
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Fields[] $project_x_fields
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProjectName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProjectIntro($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereImgProjectlogoId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereCompanyName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProvince($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereCity($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereCreateTime($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereFieldId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project wherePhaseId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProjectStatus($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProjectDesc($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProjectLightspot($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProjectFuture($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProjectTags($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereFileBpId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereInvetPhaseId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereInvet($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereMoneyType($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereSellStock($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereMinMoney($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereInvestNum($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereStopTime($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereReginvTime($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereIsFinance($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereIsSpeedFinance($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereOtherDesc($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereStarLayer($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereRepayRate($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project wherePhone($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereUserId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereProjectAuth($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereDoStatus($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereUrlId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereDeletedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereEmail($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Project whereName($value)
 * @property-read \App\User $toUser
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Images[] $project_x_overview_img
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\UserTeams[] $project_x_team
 * @method static \Illuminate\Database\Query\Builder|\App\Project like($field, $value)
 * @property integer $img_projectlogo_id
 * @method static \Illuminate\Database\Query\Builder|\App\Project searchInitByProjectNameOrProjectIntro($str)
 * @property-read mixed $fields_by_project
 */
class Project extends Model {

	//表名
    protected $table = "project" ;
    use SoftDeletes;

    /** 关联项目新闻表 */
    public function projectNews()
    {
        return $this->hasMany('App\ProjectNews' , 'project_id') ;
    }

    public function toUser()
    {
        return $this->belongsTo('App\User','user_id');
    }

//    /** 关联项目成员表 */
//    public function projectTeam()
//    {
//        return $this->hasMany('App\ProjectTeam','project_id');
//    }

    /** 关联项目里程碑表 */
    public function projectMilestone()
    {
        return $this->hasMany('App\ProjectMilestone' ,'project_id') ;
    }

    /** 关联项目logo图片信息表 */
    public function toProjectLogo()
    {
        return $this->belongsTo('App\Images','img_projectlogo_id');
    }

    /** 关联项目商业计划书路径 */
    public function toBpFile(){
        return $this->belongsTo('App\Files','file_bp_id');
    }

    /** 关联项目投资经历表 */
    public function investLog()
    {
        return $this->hasMany('App\InvestLog' , 'project_id') ;
    }

    /** 关联项目 融资阶段 */
    public function toPhase()
    {
        return $this->belongsTo('App\Phases','phase_id');
    }

    /** 关联项目的 已经融资的融资阶段 */
    public function toInvetPhase()
    {
        return $this->belongsTo('App\Phases','invet_phase_id');
    }

    /** 关联中间表-用户关注项目 */
    public function userFocusProject()
    {
        return $this->belongsToMany('App\User','focus_project','project_id','user_id');
    }

    /** 关联中间表-项目标签 */
    public function project_x_tags()
    {
        return $this->belongsToMany('App\Tags','tags_relations','project_id','tag_id');
    }

    /** 关联项目-行业领域 */
    public function project_x_fields()
    {
        return $this->belongsToMany('App\Fields','project_fields','project_id','field_id');
    }


    /** 关联项目-项目总览 */
    public function project_x_overview_img(){
        return $this->belongsToMany('App\Images' , 'overview_image' , 'project_id' , 'img_id');
    }

    /** 关联中间表-项目成员 */
    public function project_x_team()
    {
        return $this->belongsToMany('App\UserTeams','project_team','project_id','team_id');
    }

    public function getFieldsByProjectAttribute()
    {
        return $this->project_x_fields()->getResults();
    }

    /** 通过项目标识获取  已经获得的项目投资总金额 */
    public function getInvestAccountsByProjectId($projectId)
    {
        $investAccounts = InvestLog::whereProjectId($projectId)->lists('invest_account');
        $accounts = 0 ;
        if($investAccounts){
            foreach($investAccounts as $investAccount){
                $accounts += $investAccount;
            }
        }
        return $accounts;
    }

    /**
     * 通过项目标识 和链接类型获取 链接地址
     * @param $projectId
     * @param string $type
     * @return mixed
     */
    public function getProjectLink($projectId , $type='web')
    {
        $link = ProjectUrl::whereProjectId($projectId)->whereUrlType($type)->pluck('url_name');
        if($link)
            return $link;
    }

    /**
     * 判断当前项目是否已存在该标签
     * @param $projectId
     * @return mixed
     */
    public function isExistsTags($projectId)
    {
        return $this->project_x_tags()->wherePivot('project_id','=',$projectId)->exists();
    }




    /**
     * 获取当前的 融资总额
     * @param $id
     * @return int
     */
    public function getNowInvestByProId($id)
    {
        $investAccounts = InvestLog::whereProjectId($id)->lists('invest_account');
        $account = 0 ;
        if($investAccounts){
            foreach($investAccounts as $investAccount){
                $account +=$investAccount;
            }
        }
        return $account;
    }

    /**
     * 通过项目标识 获取领投人的信息
     * @param $id
     * @return array|\Illuminate\Support\Collection|null|static
     */
    public function getLeadInvestorByProId($id)
    {
        /** @var  $leadInvestorId  领投人的用户标识 */
        $userId = InvestLog::whereProjectId($id)->whereIsLead(1)->pluck('user_id');
        $leadInvestor = array() ;
        if($userId){
            $leadInvestor = UserInfo::whereUserId($userId)->first();
        }
        return $leadInvestor;
    }

    /**
     * 通过项目标识 获取跟投人的信息
     * @param $id
     * @return array|\Illuminate\Support\Collection|null|static
     */
    public function getThreadInvestorsByProId($id)
    {
        /** @var  $leadInvestorId  跟投人的用户标识 */
        $userIds = InvestLog::whereProjectId($id)->whereIsLead(0)->lists('user_id');
        $threadInvestors = array() ;
        if($userIds){
            foreach($userIds as $userId){
                if($threadInvestor = UserInfo::whereUserId($userId)->first())
                    $threadInvestors[] = $threadInvestor;
            }
        }
        return $threadInvestors;
    }

    public function scopeSearchInitByProjectNameOrProjectIntro(Builder $query,$str)
    {
        return $query->where('project_name','LIKE',"%$str%")->orWhere('project_intro','LIKE',"%$str%")->get();
    }


    public function scopeLike(Builder $query,$field,$value)
    {
        return $query->where($field,'LIKE',"%$value%");
    }

    public function getProjectUrlById($projectId,$type)
    {
        $project = Project::find($projectId);
        if(!$project)
            throw new NotFoundException(NotFoundException::ProjectNotFound);

        $urls = ProjectUrl::whereProjectId($projectId)->whereUrlType($type)->first();
        $url=null;
        if($urls)
            $url = $urls->url_name;

        return $url;
    }


    /**
     * 通过项目标识获取投资记录
     * @param $projectId
     * @return array|\Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getInvestLogByProjectId($projectId)
    {
        $investLogs = array();
        if(InvestLog::whereProjectId($projectId)->exists())
            $investLogs = InvestLog::whereProjectId($projectId)->get();
        return $investLogs;
    }

    /**
     * 通过项目标志获取项目标签
     * @param $projectId
     * @return string
     */
    public function getProjectTagsById($projectId)
    {
        $Project = Project::find($projectId);
        $tmp     = $Project->project_x_tags()->lists('tag');
        $tagStr  = '';
        if($tmp){
            foreach($tmp as $tag){
                $tagStr .= $tag.',';
            }
        }

        $tagStr = trim($tagStr , ',');
        return $tagStr ;

    }

    /**
     * 获取竞争对手数量
     * @param $proId
     * @return mixed
     */
    public function getCompeteById($proId)
    {
        if($proId < 50)
            return $proId + 2 ;
        if($proId > 50)
            return $proId - 3;
    }


    /**
     * 获取已经融资记录
     * @param $proId
     * @return array|static[]
     */
    public function getInvestLogById($proId)
    {
        $InvestLogs = InvestLog::whereProjectId($proId)->get();
        if($InvestLogs) return $InvestLogs;
    }

}
